#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

void printHTMLHead(void);
void printHTMLEnd(void);
int read(char* data, int i, char* tmp);

int main(void)
{
	printf("Content-type: text/html;charset=utf-8\n\n");
	printHTMLHead();
	int n, i, k = 0;
    char* data;
    char firstname[255];
    char lastname[255];
    char email[255];
    char reenter[255];
    char password[255];
    char selectSex[255];
    char Month[255];
    char Day[255];
    char Year[255];
    n = atoi(getenv("CONTENT_LENGTH"));
    data = (char *)malloc(n + 2);
    memset(data, '\0', n + 2);
    for(i = 0; i < (n + 1); ++i)
    {
        data[i] = getchar();
    }
    i = read(data, 0, firstname);
    k = read(data, i, lastname);
    i = read(data, k, email);
    k = read(data, i, reenter);
    i = read(data, k, password);
    k = read(data, i, selectSex);
    i = read(data, k, Month);
    k = read(data, i, Day);
    i = read(data, k, Year);
    printf("<p>Dear %s\n  %s\n! you are registered. </p>\n", firstname, lastname);

	char * filename = malloc(strlen(reenter) + 5);;
	strcpy(filename, reenter);
	strcat(filename, ".txt");
	FILE * File = fopen(filename, "wb");

    fprintf(File, "%s\n", firstname);
    fprintf(File, "%s\n", lastname);
    fprintf(File, "%s\n", email);
    fprintf(File, "%s\n", reenter);
    fprintf(File, "%s\n", password);
    fprintf(File, "%s\n", selectSex);
    fprintf(File, "%s\n", Month);
    fprintf(File, "%s\n", Day);
    fprintf(File, "%s\n", Year);
    fclose(File);
    printHTMLEnd();
    free(data);
	free(filename);
	return 0;
}

void printHTMLHead(void)
{
    printf( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n\"http://www.w3.org/TR/html4/loose.dtd\">\n" );
    printf( "<html>\n" );
    printf( "<head>\n" );
    printf( "<title>Form</title>\n" );
    printf("<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/form.css\">\n");
    printf( "</head>\n" );
    printf( "<body>\n" );
}

void printHTMLEnd(void)
{
    printf( "</body>\n" );
    printf( "</html>\n" );
}

int read(char* data, int i, char* tmp)
{
    while (data[i] != '=')
	{
		++i;
	}
	++i;
	int k = 0;
	while (data[i] != '\n')
	{
		tmp[k] = data[i];
		i++;
		k++;
    }
    tmp[k] = '\0';
	return i;
}